/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.generalfile.logic;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.common.db_service.ConfigManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

/**
 * 通用文件类逻辑处理
 *
 * @author ShiYun,2014/11/05
 */
public class GeneralFileProcess {

    private String path;
    private String messageType;
    private String policy_instance;
    private String dstPath;
    private BaseDao dao = null;
    private boolean flag = false;
    public static final String QUERY_WEB = "SELECT * FROM `shj_db`.`webcategory`";
    public static final String INSERT_WEB = "INSERT INTO `shj_db`.`webcategory` VALUES (?,?,?)";
//    public static final String QUERY_APP = "SELECT * FROM `shj_db`.`appdef`";
    public static final String QUERY_APP = "SELECT  `shj_db`.`appdef`.`AppType_id`,`shj_db`.`appdef`.`name`,`shj_db`.`apptype`.`typeName`,`shj_db`.`appdef`.`id` FROM `shj_db`.`appdef`,`shj_db`.`apptype` WHERE `shj_db`.`appdef`.`AppType_id`=`shj_db`.`apptype`.`id`";
    public static final String INSERT_APP = "INSERT INTO `shj_db`.`appdef` VALUES (?,?,?)";
    public static final String QUERY_APPTYPEID = "SELECT `id` FROM `shj_db`.`apptype` WHERE  `typeName` = ?";
    public static final String QUERY_IP_BANK = "SELECT areaName,areid FROM `shj_db`.`iprangeinfo` GROUP BY areid";
    public static final String QUERY_IP_BANKS = "SELECT * FROM `shj_db`.`iprangeinfo`";
    public static final String INSERT_IP_BANK = "INSERT INTO `shj_db`.`iprangeinfo` VALUES (0,?,?,?,?,?)";
    public static final String QUERY_WHITE = "SELECT * FROM `shj_db`.`hfdw`";
    public static final String INSERT_WHITE = "INSERT INTO `shj_db`.`hfdw` VALUES (0,?)";
    public static final String QUERY_DOMIN_BLACK = "SELECT * FROM `shj_db`.`hfdb`";
    public static final String INSERT_DOMIN_BLACK = "INSERT INTO `shj_db`.`hfdb` VALUES (0,?)";
    public static final String QUERY_URL_BLACK = "SELECT * FROM `shj_db`.`hfub`";
    public static final String INSERT_URL_BLACK = "INSERT INTO `shj_db`.`hfub` VALUES (0,?)";
    public static final String QUERY_UPLOAD_PRO_BANK = "aaa";
    public static final String QUERY_PROPERTIES = "SELECT * FROM `shj_db`.`systemproperty`";
    private String webClassifyLibrary;
    private String appTypeName;
    private String ipAddressLibrary;
    private String protocolFeatureLibrary;
    private String httpGetDomainWhite;
    private String httpGetDomainBlack;
    private String httpGetUrlBlack;
    private String commonFilePath;
    public static final String DEL_PRO_L = "truncate table pro_character_library";
    public static final String DEL_WEB = "truncate table webcategory";
    public static final String DEL_APP = "truncate table appdef";
    public static final String DEL_HTTP_DB = "truncate table hfdb";
    public static final String DEL_HTTP_UB = "truncate table hfub";
    public static final String DEL_HTTP_DW = "truncate table hfdw";
    public static final String DEL_IP_BANK = "truncate table iprangeinfo";

    public GeneralFileProcess() {
    }

    public GeneralFileProcess(String path, String messageType, String policy_instance) {
        this.path = path;
        this.messageType = messageType;
        this.policy_instance = policy_instance;
    }

    public GeneralFileProcess(String path, String messageType, String policy_instance, String dstPath) {
        this.path = path;
        this.messageType = messageType;
        this.policy_instance = policy_instance;
        this.dstPath = dstPath;
    }

    public void init() {
        dao = new BaseDao();
        flag = dao.getConnection();
    }

    public ResultSet query(String sql) {
        if (flag) {
            String[] s = {};
            ResultSet rs = dao.executeSQL(sql, s);
            return rs;
        }
        return null;
    }

    public ResultSet query(String sql, Object[] params, String page, String pageSize) {
        int no = Integer.parseInt(page) - 1;
        int size = Integer.parseInt(pageSize);
        int start = no * size - 1;
        if (start < 0) {
            start = 0;
        }
        String limit = sql + " LIMIT " + start + ", " + size;
        if (flag) {
            ResultSet rs = dao.executeSQL(limit, params);
            return rs;
        }
        return null;
    }

    public void insert(String sql, Object[] params) {
        if (flag) {
            int x = dao.executeUpdate(sql, params);
        }
    }

    public boolean delete(String sql) {
        if (flag) {
            return dao.excute(sql);
        }
        return false;
    }

    public void batch(String sql, List<String> list) {
        if (flag) {
            dao.insert(sql, list);
        }
    }

    public void close() {
        if (dao != null) {
            dao.close();
        }
    }

    public List<String> getContent(String filename, int length) {
        List<String> list = new ArrayList<>();
        try {
            File fi = new File(filename);
            if (fi.exists()) {
                InputStream is = new FileInputStream(fi);
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
                String line = null;
                int num = 0;
                while ((line = br.readLine()) != null) {
                    num++;
                    String[] ss = line.split("\t");
                    if (ss.length == length) {
                        list.add(line);
                    }
                }
                br.close();
                is.close();
                if (num == list.size()) {
                    return list;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(GeneralFileProcess.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GeneralFileProcess.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new ArrayList<>();
    }

    /*
     *存储页面上传库文件，返回存储文件路径
     */
    public String saveFile(HttpServletRequest request, String name) {
        File uploadFile = new File(ConfigManager.getInstance().getString("generalFileUploadPath"));
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        File tempPathFile = new File("/tmp/buffer");
        if (!tempPathFile.exists()) {
            tempPathFile.mkdirs();
        }
        try {
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Set factory constraints
            factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb
            factory.setRepository(tempPathFile);// 设置缓冲区目录
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8");
            // Set overall request size constraint
            upload.setSizeMax(1024 * 1024 * 10); // 设置最大文件尺寸，这里是10MB
            List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
            Iterator<FileItem> i = items.iterator();
            while (i.hasNext()) {
                System.out.println("size : " + items.size());
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // 文件操作
                    String fileName = fi.getName();
                    System.out.println("fileName : " + fileName);
                    if (fileName != null) {
                        File savedFile = new File(uploadFile, fileName);
                        FileUtils.writeStringToFile(savedFile, "");
                        fi.write(savedFile);
                        return savedFile.getAbsolutePath();
                    }
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(GeneralFileProcess.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(GeneralFileProcess.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public Map<String, Integer> getareids() {
        init();
        String query = QUERY_IP_BANK;
        ResultSet rs = query(query);
        Map<String, Integer> map = new HashMap<String, Integer>();
        try {
            while (rs != null && rs.next()) {
                String name = rs.getString(1);
                int value = rs.getInt(2);
                map.put(name, value);
            }
        } catch (SQLException ex) {
        }
        close();
        return map;
    }

    public void getProperties() {
        init();
        String query = QUERY_PROPERTIES;
        ResultSet rs = query(query);
        try {
            while (rs != null && rs.next()) {
                String name = rs.getString(1);
                String value = rs.getString(2);
//                System.out.println("name:" + name + ", value:" + value);
                if (name.equals("web.classify.library.name")) {
                    this.webClassifyLibrary = value;
                }
                if (name.equals("apptype.appname.name")) {
                    this.appTypeName = value;
                }
                if (name.equals("ip.address.library.name")) {
                    this.ipAddressLibrary = value;
                }
                if (name.equals("protocol.feature.library.name")) {
                    this.protocolFeatureLibrary = value;
                }
                if (name.equals("htppget.domain.white.name")) {
                    this.httpGetDomainWhite = value;
                }
                if (name.equals("httpget.domain.black.name")) {
                    this.httpGetDomainBlack = value;
                }
                if (name.equals("httpget.url.black.name")) {
                    this.httpGetUrlBlack = value;
                }
                if (name.equals("common.file.path")) {
                    this.commonFilePath = value;
                }
            }
        } catch (SQLException ex) {
        }
        close();
    }

    public String getWebClassifyLibrary() {
        return webClassifyLibrary;
    }

    public String getAppTypeName() {
        return appTypeName;
    }

    public String getIpAddressLibrary() {
        return ipAddressLibrary;
    }

    public String getProtocolFeatureLibrary() {
        return protocolFeatureLibrary;
    }

    public String getHttpGetDomainWhite() {
        return httpGetDomainWhite;
    }

    public String getHttpGetDomainBlack() {
        return httpGetDomainBlack;
    }

    public String getHttpGetUrlBlack() {
        return httpGetUrlBlack;
    }

    public String getCommonFilePath() {
        return commonFilePath;
    }

    public static void main(String[] args) {
        GeneralFileProcess gn = new GeneralFileProcess();
        gn.getProperties();
    }
}
